package com.zx.ishopping.services.impl;

import com.zx.ishopping.Constants.InsertConstant;
import com.zx.ishopping.VO.AddressVO;
import com.zx.ishopping.entity.Address;
import com.zx.ishopping.exceptions.AddressException;
import com.zx.ishopping.mapper.AddressMapper;
import com.zx.ishopping.services.AddressService;
import com.zx.ishopping.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Override
    public List<AddressVO> getAddress() {
        //获取用户id
        Long userId = ThreadLocalUtil.get();
        List <AddressVO> addressVOList = addressMapper.getAddress(userId);
        return addressVOList;
    }


    /**
     * 添加商品地址
     * @param address
     */
    @Override
    public void addAddress(Address address) {
        
        Long userId = ThreadLocalUtil.get();
        //每人最多创建10个地址
        if (addressMapper.getAddress(userId).size() >= 10){
            throw new AddressException(InsertConstant.NUMBER_OF_ADDRESSES_EXCEEDS_LIMIT);
        }
        
        
        
        //判断新地址是否为默认地址
        if (address.getIsDefault() == 1){
            //将原先的默认地址改为非默认
            addressMapper.updateDefault(userId);
        }
        //修改之后再添加新的地址
        address.setUserId(userId);
        addressMapper.addAddress(address);
    }

    /**
     * 删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        Long userId = ThreadLocalUtil.get();
        addressMapper.deleteAddress(id,userId);
    }

    /**
     * 修改地址
     * @param address
     */
    @Override
    public void updateAddress(Address address) {
        Long userId = ThreadLocalUtil.get();
        address.setUserId(userId);
        
        //如果isDefault为1，则说明修改了默认地址
        if ( address.getIsDefault() == 1){
            addressMapper.updateDefault(userId);
        }
        
        addressMapper.updateAddress(address);
        
        
        
    }
}
